package com.sctvcloud.renhe.ui.activities;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.beans.JSBeans;
import com.sctvcloud.renhe.beans.MallJsonVo;
import com.sctvcloud.renhe.utils.UserManager;

import org.json.JSONObject;

/**
 * Created by Liuyu on 2018/8/21.
 */

public abstract class BaseIntegralWebActivity extends BaseActivity {

    protected WebView webView;


    protected String url;
    protected String token;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = (WebView) findViewById(getWevViewId());
        initWebView();
    }

    protected abstract int getWevViewId();

    protected void initWebView() {
//        WebSettings settings = webView.getSettings();
//        // 使用缓存
//        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        String ua = settings.getUserAgentString();
//        settings.setUserAgentString(ua + " SCGC_UA");
////        settings.getUserAgentString()
//        //使h5页面适应手机屏幕
//        settings.setUseWideViewPort(true);
//        settings.setLoadWithOverviewMode(true);
//        //设置可以支持缩放
//        settings.setSupportZoom(true);
//        //设置出现缩放工具
//        settings.setBuiltInZoomControls(true);
//        //隐藏缩放工具
//        settings.setDisplayZoomControls(false);
//        //扩大比例的缩放
//        settings.setUseWideViewPort(true);
//        // 支持JavaScript
//        settings.setJavaScriptEnabled(true);
//        settings.setMediaPlaybackRequiresUserGesture(false);

        webView.setWebChromeClient(new WebChromeClient() {
            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//                Log.i("test", "openFileChooser 3");
//                IntegralStoreActivity.this.uploadFile = uploadFile;
//                openFileChooseProcess(null);
            }

        });
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http://")&&!url.startsWith("https://")) {
                    return true;
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String titleStr = view.getTitle();
                if (!TextUtils.isEmpty(titleStr)) {
//                    if (TextUtils.isEmpty(title)){
//                    title = titleStr;
//                    }
                }
            }
        });
        webView.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void callRouter(String s1, String s2) {
                //H5页面调用Android原生代码
                if (!TextUtils.isEmpty(s1)) {
                    try {
                        JLog.e("htmlLogin", "-----------------------s1-" + s1 + "----s2" + s2);
//                        JSONObject jso = new JSONObject(s1);
                        MallJsonVo jsonBean = new Gson().fromJson(s1, MallJsonVo.class);
                        JLog.e("wwwww,  jsbean=" + jsonBean.toAllString());
                        parseJSMethod(jsonBean);
//                        String actId =
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }, "bridge");
        initWebSetting();
        Intent intent = getIntent();
        if (UserManager.isLoginS()) {
            token = UserManager.getInstance().getToken();
        }
        if (intent != null) {
            url = intent.getStringExtra(EX_HTML);
            if (!TextUtils.isEmpty(url)) {
                JLog.e("htmlLogin", "----------load-------------token-" + token);
                if (!TextUtils.isEmpty(token)) {
                    webView.loadUrl(url + "?token=" + token);
                } else {
                    webView.loadUrl(url);
                }
            }
        }
//        CookieSyncManager.createInstance(this);
//        CookieSyncManager.getInstance().sync();
    }

    protected void initWebSetting() {
        WebSettings webSetting = webView.getSettings();
        String ua = webSetting.getUserAgentString();
        webSetting.setUserAgentString(ua + " SCGC_UA");

        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
    }

    /**
     * 回调的方法解析判断
     */
    private void parseJSMethod(MallJsonVo jsb) {
        if (jsb == null) {
            return;
        }
        String method = jsb.getMethod().trim();
        if ("Login".equalsIgnoreCase(method)) {
            //H5回调，判断是否已登录
            if (UserManager.isLoginS()) {
                token = UserManager.getInstance().getToken();
                if (!TextUtils.isEmpty(token)) {
                    JLog.e("htmlLogin", "-------is login-----token = " + token);
                } else {
                    toLogin();
                }
            } else {
                toLogin();
            }
        } else {
            parseOtherJSMethod( jsb);
        }
    }

    protected void parseOtherJSMethod(MallJsonVo bean) {
    }

    protected void loadUrl(String url) {
        webView.loadUrl(url);
    }
}
